'use strict';
//define(['common','angular','services'], function(common,angular) {
	angular.module('backcenter.orgauth', ['app.treeView'])

	.controller('orgauthCtrl'
			,['$rootScope', '$scope', '$stateParams', '$state', '$uibModal', 'BizData'
				, '$ocLazyLoad'
	        , f])//控制器结束
    function f($rootScope, $scope, $stateParams, $state, $uibModal, BizData
    		, $ocLazyLoad
	          ) {

		var Model = this;
		
		
		/**
		name:bizData#onAfterRefresh
		description: <b>[回调型事件]</b>业务数据刷新后
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
			"source" : 组件的js对象
			"limit" : 页大小, 
			"offset" : 偏移,
			"success" : 是否成功刷新
		}
		</xmp>	
		*/
		Model.dataOrgAfterRefresh = function(event){
			var dataTree = event.source;
			//展开第一个
			var rowID = dataTree.getCurrentID();
			if(rowID!=null){
				dataTree.expandRow(rowID);
			}
		};
		
	
		
		/**
		name:bizData#onIndexChanged
		description: <b>[回调型事件]</b>行记录变化
		@param {object} event 
		<br/><b>结构如下：</b>
		<xmp> 
		{
		"source" : 组件的js对象,
		"rowID" : 行Id,
		"rowIndex" : 行索引
		}
		</xmp>	
		*/
		Model.dataOrgIndexChanged = function(event) {
			if(event.rowID){
				$scope.dataAuthorize.filter = "sOrgID='"+ event.rowID +"'";// AND sOrgKindID='ogn' AND sValidState=1 ";
				$scope.dataAuthorize.refreshData();
			}
		}

		
		
//		$scope.objects = {"$scope.dataOrg" : $scope.dataOrg,"$scope.dataAuthorize" : $scope.dataAuthorize};
		

		
		////////////////////////////////////////////////////////////////////////////////////////

		
		//打开对话框（选择角色）
		Model.triggerSelectRoleClick = function(){
			var options = {};
			
			options.recordState = 'edit';
			options.id =  $rootScope.topMyOgn.sID;

	        var modalInstance = $uibModal.open({  
	        	backdrop: 'static',
	        	size: 'lg',
	            templateUrl: $rootScope.getProjectName() + '/backcenter/role/selectMulti',  
	            controller: 'roleSelectMultiCtrl as Model',  
	            resolve: {
	                params: function () {  
	                    return angular.copy(options);  
	                }
                    ,title : function() { return '选择'; }
                    ,loadCtrl : $ocLazyLoad.load('js/role/selectMulti')
		        }
	        });  
	        //模态窗口关闭之后执行的事件
	        modalInstance.result.then(function (event) {  
	             //成功关闭窗口
	         	var returnData = event.data;
	         	//debugger;
	             try {
	            	 
	            	//选择的角色的ids
	             	var roleIDs = new Array();
	            	 
	             	for ( var i = 0; i < returnData.length; i++) {
	             		
//	         			dataDetail.setValue('sPersonID', returnData[i].sID, rowID);
//	         			dataDetail.setValue('sName', returnData[i].sName, rowID);
//	         			dataDetail.setValue('sCode', returnData[i].sCode, rowID);
//	         			dataDetail.setValue('sLongName', returnData[i].sLongName, rowID);
//	         			dataDetail.setValue('sID', dataDetail.getValue('sParent',rowID) + '@' + returnData[i].sID, rowID);
//	             		roleIDs[i] = returnData[i].sID;
	             		roleIDs.push(returnData[i].sID);
	                 }
	             	if(roleIDs.length<=0){
	             		return 0;
	             	}
	             	
	             	//当前组织的ids
             		var dataDetail = $scope.dataOrg;
             		var rowID = dataDetail.getCurrentID();
             		var orgIDs = new Array();
             		orgIDs[0] = rowID; 
             		
             		var data = {};
             		data.orgIDs = orgIDs;
            		data.roleIDs = roleIDs;
	             	
	    			//提交保存
//	    			var response = authorizeService.add(data);
					var response = $.ajax({
			            type: "POST",
			            async : false,
			            url: $rootScope.getProjectName() + "/backcenter/orgauth/list/add",
			            data: JSON.stringify(data),// "{}",
			            contentType: "application/json; charset=utf-8",
			            dataType: "json",
//			            processData: false,
			            success: function (data) {
			                // Play with returned data in JSON format
			            },
			            error: function (msg) {
//			                alert(msg.responseText);
			            }
			        });
	    			
	    			if (response.readyState == 4 && response.status == 200) {
	    				$scope.dataAuthorize.refreshData();
	    				return 0;
	    			}else{
	    				alert('保存失败！')
	    				return -1;
	    			}

	             } finally {
	             	return;
	             }

	        }, function (reason) {  
	            console.info('Modal dismissed at: ' + new Date());  
	        });  
			
		}

		
		var options = {};
		options.container = Model;
		options.concept = 'SaOporg';
		options.name = 'dataOrg';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
		options.creater = '/backcenter/org/tree/create';
		options.reader = '/backcenter/org/tree/query';
		options.writer = '/backcenter/org/tree/save';
		options.deleter = '/backcenter/org/tree/delete';
		options.idColumnDefine = "sID";
		options.idColumnName = "sID";
		options.defCols = {sID:{name:"sID",type:"String",label:""},sName:{name:"sName",type:"String",label:""},sCode:{name:"sCode",type:"String",label:""},sLongName:{name:"sLongName",type:"String",label:""},sFName:{name:"sFName",type:"String",label:""},sFCode:{name:"sFCode",type:"String",label:""},sFID:{name:"sFID",type:"String",label:""},sOrgKindID:{name:"sOrgKindID",type:"String",label:""},sSequence:{name:"sSequence",type:"String",label:""},sValidState:{name:"sValidState",type:"Integer",label:""},sParent:{name:"sParent",type:"String",label:""},sNodeKind:{name:"sNodeKind",type:"String",label:""},sLevel:{name:"sLevel",type:"Integer",label:""},sPhone:{name:"sPhone",type:"String",label:""},sFax:{name:"sFax",type:"String",label:""},sAddress:{name:"sAddress",type:"String",label:""},sZip:{name:"sZip",type:"String",label:""},sDescription:{name:"sDescription",type:"String",label:""},sPersonID:{name:"sPersonID",type:"String",label:""},sCreatorFID:{name:"sCreatorFID",type:"String",label:""},version:{name:"version",type:"Integer",label:""}};
		options.isTree = true;
		options.parentRelation = 'sParent';
		options.nodeKindRelation = 'sNodeKind';
		options.nodeLevelRelation = 'sLevel';
		options.nodeSortRelation = "sSequence";
		options.pathRelation = 'sFID';
		options.directDeleteMode = false;
   		options.limit = -1;
		options.orderBy = 'sSequence ASC';
		
		options.onIndexChanging = null;
		options.onIndexChanged = Model.dataOrgIndexChanged;
		options.onAfterRefresh = Model.dataOrgAfterRefresh;
		
		$scope.dataOrg = new BizData(options);

		//监视对象中的所有变动
		$scope.dataOrg.deregRows = $scope.$watch('dataOrg.rows',$scope.dataOrg.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////

		
		var options = {};
		options.container = Model;
		options.concept = 'SaOpauthorize';
		options.name = 'dataAuthorize';
		options.url = $rootScope.path;
		options.httpUrl = $rootScope.getServiceName();
		options.creater = '/backcenter/orgauth/list/create';
		options.reader = '/backcenter/orgauth/list/query';
		options.writer = '/backcenter/orgauth/list/save';
		options.deleter = '/backcenter/orgauth/list/delete';
		options.idColumnDefine = "sID";
		options.idColumnName = "sID";
		options.defCols = {sID:{name:"sID",type:"String",label:""},sAuthorizeRoleID:{name:"sAuthorizeRoleID",type:"String",label:""},sDescription:{name:"sDescription",type:"String",label:""},sOrgID:{name:"sOrgID",type:"String",label:""},sOrgName:{name:"sOrgName",type:"String",label:""},sOrgFID:{name:"sOrgFID",type:"String",label:""},sOrgFName:{name:"sOrgFName",type:"String",label:""},sCreatorFID:{name:"sCreatorFID",type:"String",label:""},sCreatorFName:{name:"sCreatorFName",type:"String",label:""},sCreateTime:{name:"sCreateTime",type:"Datetime",label:""},version:{name:"version",type:"Integer",label:""}};
		options.isTree = false;
		options.parentRelation = 'sParent';
		options.nodeKindRelation = 'sNodeKind';
		options.nodeLevelRelation = 'sLevel';
		options.nodeSortRelation = "sSequence";
		options.pathRelation = 'sFID';
		options.directDeleteMode = false;
		
		$scope.dataAuthorize = new BizData(options);

		//监视对象中的所有变动
		$scope.dataAuthorize.deregRows = $scope.$watch('dataAuthorize.rows',$scope.dataAuthorize.watchRows,true);//true代表深度监视，包括对象的属性，而不是简单的一个值
		//////////////////////////////////////////////

		/*
		//添加权限//跳转到按组织授权页面
		Model.addAuthorizations = function(item) {
			var id = item.sID.value;
			var to = '/backcenter/orgauth/treeList';
			var params = {
					"id":id
					,"sLongName":item.sLongName.value
					,"sName":item.sName.value
					,"recordState":"none"
					};
			var options = {};
			$state.go(to,params,options);
		}
		*/
		
		//接收调用的参数
//		Model.params = $stateParams; 
//		console.log('Model.params-->',Model.params);

    	
    	if($rootScope.checkTopMyOgn()==true){
    		//设置过滤条件
    		$scope.dataOrg.filter = "SaOporg.sFID like '%"+  $rootScope.topMyOgn.sID +"%'";//+" AND sOrgKindID='ogn'";
//    		$scope.dataOrg.filter = "SaOporg.sCreatorFID = '"+  $rootScope.topMyOgn.sID +"'";//+" AND sOrgKindID='ogn'";
    		$scope.dataOrg.refreshData();
//    		$scope.dataAuthorize.refreshData();
    	}

	    
	    ///////////////////////////页面级////////////////////////////////////////
		//返回
		Model.goBack = function(event) {
			window.history.go(-1);
		}
	    ///////////////////////////页面级////////////////////////////////////////

		//（删除权限）
		Model.triggerDeleteAuthorizeClick = function(){
			var ids = new Array();
			for(var index=0;index<$scope.dataAuthorize.rows.length;index++){
				if($scope.dataAuthorize.rows[index].userdata.checked){
					ids.push($scope.dataAuthorize.rows[index].sID.value);
				}
			}
			$scope.dataAuthorize.deleteData(ids);
			$scope.dataAuthorize.refreshData();
		}

	    //表格标题中的选择框ng-model
	    $scope.checkboxValue = false;
	    //表格标题中的选择对话框click事件
	    Model.checkboxClick = function () {  
			for(var index=0;index<$scope.dataAuthorize.rows.length;index++){
				$scope.dataAuthorize.rows[index].userdata.checked=$scope.checkboxValue;
			}
	    };    
		
		
	    return Model;

	}	
	
//});
